package com.intelligent.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class SmsCodeUtils {

    private static final Logger logger = LoggerFactory.getLogger(SmsCodeUtils.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisManagementUtils redisManagementUtils;

    // Redis存储验证码的key前缀
    @Value("${aliyun.sms.redis-key-prefix:sms:code:}")
    private String redisKeyPrefix;

    // 验证码有效期，固定为3分钟
    private static final int EXPIRE_TIME = 3;

    /**
     * 生成6位随机验证码
     */
    public String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 存储验证码到Redis，有效期3分钟
     */
    public void saveCodeToRedis(String phone, String code) {
        String redisKey = redisKeyPrefix + phone;
        int retryCount = 0;
        int maxRetries = 2;
        
        while (retryCount <= maxRetries) {
            try {
                // 明确设置为3分钟过期
                redisTemplate.opsForValue().set(redisKey, code, EXPIRE_TIME, TimeUnit.MINUTES);
                logger.info("Successfully saved SMS code to Redis for phone: {}", phone);
                return;
            } catch (Exception e) {
                logger.error("Failed to save SMS code to Redis (attempt {}): {}", retryCount + 1, e.getMessage());
                
                if (e.getMessage() != null && e.getMessage().contains("READONLY")) {
                    logger.warn("Redis is in read-only mode, attempting to fix...");
                    try {
                        redisManagementUtils.checkAndFixRedisStatus();
                        Thread.sleep(1000); // 等待1秒让Redis处理
                    } catch (Exception fixException) {
                        logger.error("Failed to fix Redis status: {}", fixException.getMessage());
                    }
                }
                
                retryCount++;
                if (retryCount > maxRetries) {
                    logger.error("Failed to save SMS code after {} attempts, giving up", maxRetries + 1);
                    throw new RuntimeException("Unable to save SMS code to Redis: " + e.getMessage(), e);
                }
                
                try {
                    Thread.sleep(500 * retryCount); // 递增延迟重试
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Interrupted while retrying Redis operation", ie);
                }
            }
        }
    }

    /**
     * 从Redis获取验证码
     */
    public String getCodeFromRedis(String phone) {
        String redisKey = redisKeyPrefix + phone;
        return redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 登录成功后删除Redis中的验证码
     */
    public void deleteCodeFromRedis(String phone) {
        String redisKey = redisKeyPrefix + phone;
        redisTemplate.delete(redisKey);
    }
}
